import { Injectable, BadRequestException, InternalServerErrorException, Inject } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Between } from 'typeorm';
import { Order, OrderStatus } from '../entity/order.entity';
import { User } from '../entity/user.entity';
import { Product } from '../entity/product.entity';
// import { Category } from '../entity/category.entity';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';

interface DailyStats {
  date: string;
  totalAmount: number;
  orderCount: number;
}

interface DailyStatsMap {
  [key: string]: DailyStats;
}

@Injectable()
export class StaticService {
  constructor(
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Product)
    private readonly productRepository: Repository<Product>,
    // @InjectRepository(Category)
    // private readonly categoryRepository: Repository<Category>,
    @Inject(CACHE_MANAGER)
    private readonly cacheManager: Cache,
  ) {}

  private async validateDateRange(startDate: Date, endDate: Date) {
    if (startDate > endDate) {
      throw new BadRequestException('开始日期不能大于结束日期');
    }
    if (endDate > new Date()) {
      throw new BadRequestException('结束日期不能大于当前日期');
    }
  }

  async getOverview() {
    try {
      const cacheKey = 'statistics:overview';
      const cachedData = await this.cacheManager.get(cacheKey);
      if (cachedData) {
        return cachedData;
      }

      const [
        totalUsers,
        totalOrders,
        totalProducts,
        // totalCategories,
        totalRevenue,
        recentOrders,
      ] = await Promise.all([
        this.userRepository.count(),
        this.orderRepository.count(),
        this.productRepository.count(),
        // this.categoryRepository.count(),
        this.orderRepository
          .createQueryBuilder('order')
          .select('SUM(order.totalAmount)', 'total')
          .where('order.status = :status', { status: OrderStatus.COMPLETED })
          .getRawOne(),
        this.orderRepository.find({
          relations: ['user'],
          order: { createdAt: 'DESC' },
          take: 5,
        }),
      ]);

      const result = {
        totalUsers,
        totalOrders,
        totalProducts,
        // totalCategories,
        totalRevenue: parseFloat(totalRevenue.total) || 0,
        recentOrders,
      };

      // 缓存5分钟
      await this.cacheManager.set(cacheKey, result, 300000);
      return result;
    } catch (error) {
      throw new InternalServerErrorException('获取概览数据失败');
    }
  }

  async getSalesStatistics(startDate: Date, endDate: Date) {
    try {
      await this.validateDateRange(startDate, endDate);

      const cacheKey = `statistics:sales:${startDate.toISOString()}:${endDate.toISOString()}`;
      const cachedData = await this.cacheManager.get(cacheKey);
      if (cachedData) {
        return cachedData;
      }

      const orders = await this.orderRepository.find({
        where: {
          createdAt: Between(startDate, endDate),
          status: OrderStatus.COMPLETED,
        },
        select: ['createdAt', 'totalAmount'],
        order: { createdAt: 'ASC' },
      });

      const dailyStats = orders.reduce<DailyStatsMap>((acc, order) => {
        const date = order.createdAt.toISOString().split('T')[0];
        if (!acc[date]) {
          acc[date] = {
            date,
            totalAmount: 0,
            orderCount: 0,
          };
        }
        acc[date].totalAmount += order.totalAmount;
        acc[date].orderCount += 1;
        return acc;
      }, {});

      const result = {
        dailyStats: Object.values(dailyStats),
        totalAmount: orders.reduce((sum, order) => sum + order.totalAmount, 0),
        totalOrders: orders.length,
      };

      // 缓存1小时
      await this.cacheManager.set(cacheKey, result, 3600000);
      return result;
    } catch (error) {
      if (error instanceof BadRequestException) {
        throw error;
      }
      throw new InternalServerErrorException('获取销售统计数据失败');
    }
  }

  async getCategoryStatistics() {
    // try {
    //   const cacheKey = 'statistics:categories';
    //   const cachedData = await this.cacheManager.get(cacheKey);
    //   if (cachedData) {
    //     return cachedData;
    //   }

    //   const categories = await this.categoryRepository.find({
    //     relations: ['products'],
    //   });

    //   const result = categories.map(category => ({
    //     id: category.id,
    //     name: category.name,
    //     productCount: category.products.length,
    //   }));

    //   // 缓存1小时
    //   await this.cacheManager.set(cacheKey, result, 3600000);
    //   return result;
    // } catch (error) {
    //   throw new InternalServerErrorException('获取分类统计数据失败');
      // }
      return
  }

  async getTopProducts(limit: number = 10) {
    try {
      const cacheKey = `statistics:top-products:${limit}`;
      const cachedData = await this.cacheManager.get(cacheKey);
      if (cachedData) {
        return cachedData;
      }

      const result = await this.productRepository
        .createQueryBuilder('product')
        .leftJoin('product.orderItems', 'orderItem')
        .leftJoin('orderItem.order', 'order')
        .select('product.id', 'id')
        .addSelect('product.name', 'name')
        .addSelect('product.price', 'price')
        .addSelect('COUNT(orderItem.id)', 'orderCount')
        .addSelect('SUM(orderItem.quantity)', 'totalQuantity')
        .addSelect('SUM(orderItem.price * orderItem.quantity)', 'totalRevenue')
        .where('order.status = :status', { status: OrderStatus.COMPLETED })
        .groupBy('product.id')
        .orderBy('totalRevenue', 'DESC')
        .limit(limit)
        .getRawMany();

      // 缓存30分钟
      await this.cacheManager.set(cacheKey, result, 1800000);
      return result;
    } catch (error) {
      throw new InternalServerErrorException('获取热门商品统计数据失败');
    }
  }

  async getUserStatistics() {
    try {
      const cacheKey = 'statistics:users';
      const cachedData = await this.cacheManager.get(cacheKey);
      if (cachedData) {
        return cachedData;
      }

      const users = await this.userRepository
        .createQueryBuilder('user')
        .leftJoin('user.orders', 'order')
        .select('user.id', 'id')
        .addSelect('user.username', 'username')
        .addSelect('COUNT(order.id)', 'orderCount')
        .addSelect('SUM(order.totalAmount)', 'totalSpent')
        .where('order.status = :status', { status: OrderStatus.COMPLETED })
        .groupBy('user.id')
        .orderBy('totalSpent', 'DESC')
        .getRawMany();

      const result = users.map(user => ({
        id: user.id,
        username: user.username,
        orderCount: parseInt(user.orderCount) || 0,
        totalSpent: parseFloat(user.totalSpent) || 0,
      }));

      // 缓存1小时
      await this.cacheManager.set(cacheKey, result, 3600000);
      return result;
    } catch (error) {
      throw new InternalServerErrorException('获取用户统计数据失败');
    }
  }

  async getOrderStatusStatistics() {
    try {
      const cacheKey = 'statistics:order-status';
      const cachedData = await this.cacheManager.get(cacheKey);
      if (cachedData) {
        return cachedData;
      }

      const stats = await this.orderRepository
        .createQueryBuilder('order')
        .select('order.status', 'status')
        .addSelect('COUNT(order.id)', 'count')
        .groupBy('order.status')
        .getRawMany();

      const result = stats.map(stat => ({
        status: stat.status as OrderStatus,
        count: parseInt(stat.count),
      }));

      // 缓存30分钟
      await this.cacheManager.set(cacheKey, result, 1800000);
      return result;
    } catch (error) {
      throw new InternalServerErrorException('获取订单状态统计数据失败');
    }
  }
}
